package cn.sciento.starter.sms.support;

import cn.sciento.core.exception.CommonException;
import com.aliyuncs.AcsRequest;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
import java.util.Map;
import cn.sciento.starter.sms.entity.SmsConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

public class AliyunSmsSupporter {
  private static final Logger logger = LoggerFactory.getLogger(AliyunSmsSupporter.class);
  
  private static final String PRODUCT = "Dysmsapi";
  
  private static final String DOMAIN = "dysmsapi.aliyuncs.com";
  
  private static final String REGION_ID = "cn-hangzhou";
  
  public static IAcsClient acsClient(SmsConfig smsConfig) {
    System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
    System.setProperty("sun.net.client.defaultReadTimeout", "10000");
    DefaultProfile defaultProfile = DefaultProfile.getProfile("cn-hangzhou", smsConfig.getAccessKey(), smsConfig.getAccessKeySecret());
    try {
      DefaultProfile.addEndpoint(smsConfig.getEndPoint(), "cn-hangzhou", "Dysmsapi", "dysmsapi.aliyuncs.com");
    } catch (ClientException e) {
      logger.error("Unable to generate Acs Client : {}", e.fillInStackTrace());
      throw new CommonException(e);
    } 
    return new DefaultAcsClient(defaultProfile);
  }
  
  public static SendSmsResponse sendSms(IAcsClient acsClient, SmsConfig smsConfig, String externalCode, List<String> receiverAddress, Map<String, String> args, ObjectMapper objectMapper) throws ClientException, JsonProcessingException {
    SendSmsRequest request = new SendSmsRequest();
    request.setPhoneNumbers(StringUtils.collectionToCommaDelimitedString(receiverAddress));
    request.setSignName(smsConfig.getSignName());
    request.setTemplateCode(externalCode);
    request.setTemplateParam(objectMapper.writeValueAsString(args));
    return acsClient.getAcsResponse(request);
  }
}
